// pages/ranking/ranking.js

// 添加宿舍等级判定函数
function getDormLevel(score) {
  if (score >= 90) return "优秀宿舍";
  if (score >= 75) return "良好宿舍";
  if (score >= 60) return "合格宿舍";
  return "不合格宿舍";
}

Page({

  /**
   * 页面的初始数据
   */
  data: {
    dorms: [],
    filteredDorms: [],
    isLoading: true,
    activeTab: 'all', // 当前选中的标签: all, excellent, good, pass, fail
    activeBuilding: '', // 当前选中的楼栋: 空字符串表示全部楼栋
    buildings: [], // 所有楼栋列表
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.fetchDorms();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    // 每次显示页面时刷新数据
    this.fetchDorms();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    this.fetchDorms().then(() => {
      wx.stopPullDownRefresh();
    });
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },

  // 获取所有宿舍数据
  fetchDorms: async function() {
    this.setData({ isLoading: true });
    
    try {
      const db = wx.cloud.database();
      
      // 获取宿舍数据
      const res = await db.collection('dorms')
        .orderBy('currentScore', 'desc')
        .get();
      
      if (res.data && res.data.length > 0) {
        // 处理宿舍数据，添加等级信息和排名
        const dorms = res.data.map((dorm, index) => {
          dorm.level = getDormLevel(dorm.currentScore);
          dorm.rank = index + 1;
          dorm.displayName = `${dorm.building}栋${dorm.roomNo}`;
          return dorm;
        });
        
        // 获取所有楼栋
        const buildings = [...new Set(dorms.map(dorm => dorm.building))].sort();
        
        this.setData({ 
          dorms,
          filteredDorms: dorms,
          buildings,
          isLoading: false
        });
        
        // 应用默认过滤器
        this.applyFilters();
      } else {
        this.setData({ 
          dorms: [],
          filteredDorms: [],
          buildings: [],
          isLoading: false
        });
      }
    } catch (err) {
      console.error('获取宿舍数据失败', err);
      wx.showToast({
        title: '获取数据失败',
        icon: 'none'
      });
      this.setData({ isLoading: false });
    }
  },
  
  // 切换标签
  switchTab: function(e) {
    const tab = e.currentTarget.dataset.tab;
    this.setData({ activeTab: tab });
    this.applyFilters();
  },
  
  // 切换楼栋
  switchBuilding: function(e) {
    const building = e.currentTarget.dataset.building;
    this.setData({ activeBuilding: building });
    this.applyFilters();
  },
  
  // 应用过滤器
  applyFilters: function() {
    const { dorms, activeTab, activeBuilding } = this.data;
    
    // 先根据楼栋过滤
    let filtered = dorms;
    if (activeBuilding) {
      filtered = filtered.filter(dorm => dorm.building === activeBuilding);
    }
    
    // 再根据标签过滤
    if (activeTab !== 'all') {
      switch(activeTab) {
        case 'excellent':
          filtered = filtered.filter(dorm => dorm.currentScore >= 90);
          break;
        case 'good':
          filtered = filtered.filter(dorm => dorm.currentScore >= 75 && dorm.currentScore < 90);
          break;
        case 'pass':
          filtered = filtered.filter(dorm => dorm.currentScore >= 60 && dorm.currentScore < 75);
          break;
        case 'fail':
          filtered = filtered.filter(dorm => dorm.currentScore < 60);
          break;
      }
    }
    
    // 更新过滤后的宿舍数据，并重新计算排名
    filtered = filtered.map((dorm, index) => {
      dorm.rank = index + 1;
      return dorm;
    });
    
    this.setData({ filteredDorms: filtered });
  },
  
  // 跳转到宿舍详情
  goToDormDetail: function(e) {
    const dormId = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/dormDetail/dormDetail?id=${dormId}`
    });
  }
})